<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
    <el-form-item label="工单号/任务单号" prop="workTaskNumber">
        <el-input
          v-model="queryParams.workTaskNumber"
          placeholder="请输入工单号/任务单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部件编号" prop="partNumber">
        <el-input
          v-model="queryParams.partNumber"
          placeholder="请输入部件编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> 
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="partDrawingNumber">
        <el-input
          v-model="queryParams.partDrawingNumber"
          placeholder="请输入部件图纸图号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序名称" prop="dictProcessName" >
        <el-select
          v-model="queryParams.dictProcessName"
          placeholder="请选择工序名称"
          clearable
        >
          <el-option
            v-for="dict in getIntDictOptions('craft_process_name')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="dictProductiveTaskStatus">
        <el-select
          v-model="queryParams.dictProductiveTaskStatus"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in stateOptionsList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <div  class="btnWrap">
    <div>
        <el-button
          type="primary"
          @click="openForm('works',id)"
          v-hasPermi="['produce:production-task-order:works']"
        >
        批量派工
        </el-button>
        <el-button
          type="primary"
          @click="sumbit"
          v-hasPermi="['produce:production-task-order:submit']"
        >
        批量提交
        </el-button>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['produce:production-task-order:export']"
        >
         数据导出
        </el-button>
      </div>
        <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
  </div>
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length?true:false"
      @register="tableoperation"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :tableHeight="tableHeight"
      >
      <template #action="{ row }">
        <cell>
          <el-button link type="primary" v-if="[10,20,50,60].includes(row.dictProductiveTaskStatus)" @click="openForm('work', row.id)">派工</el-button> 
          <el-button link type="primary" v-if="[10].includes(row.dictProductiveTaskStatus)"   @click="sumbitRow(row)">提交</el-button>
          <el-button link type="primary" @click="openForm('details', row.id)">查看</el-button>
        </cell>
      </template>
    </Table>
  </ContentWrap>
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getLabelAll" />
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
</template>

<script setup name="ProductionTaskOrder">
import { getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import * as ProductionTaskOrderApi from '@/api/produce/workOrderManagement/productionTaskOrder'
let  tableTitleList = ref([]) // 表头的数据
const loading = ref(true) // 列表的加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  creatorName: null,
  createTime: [],
  workTaskNumber: null,
  productNumber: null,
  productName: null,
  productStandard: null,
  productDrawingNumber: null,
  orderQuantity: null,
  partNumber: null,
  partName: null,
  partDrawingNumber: null,
  partSpecification: null,
  processName: null,
  productiveTaskStatus: null,
  netSizeLength: null,
  netSizeWidth: null,
  cuttingSizeLength: null,
  cuttingSizeWidth: null,
  dictIsMachine: null,
  jobNumber: null,
  basicDosage: null,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
// const total = ref(0) // 列表的总页数
// const list = ref([]) // 列表的数据

// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作getUserLabelPage
// 详细可见：https://doc.iocoder.cn/vue3/crud-schema/
const { tableObject,tableMethods } = useTable({
  getListApi: ProductionTaskOrderApi.getProductionTaskOrderPage, // 分页接口
  defaultParams:queryParams
})


/**表头数据 */
const getLabelAll = async () => {
  loading.value = true
  try {
    const res = await ProductionTaskOrderApi.getProductionTaskOrderPage(queryParams)
    res.labels.push({
        label: '操作',
        field: 'action',
        isDetail: false,
        width: 160
    })
    const {allSchemas} = useCrudSchemas(res.labels)
    tableTitleList.value = allSchemas.tableColumns;
    /**表头修改需要刷新表格 */
    getList()
  } finally {
    loading.value = false
  }
}

/** 导出按钮操作 */
const exportRef = ref()
  const handleExport = () => {
    exportRef.value.open()
  }

/**打开表格表头设置**/
const tableTitleSet = ref() 
const openTableTitleSet = () => {
  // const arr = tableTitleList.value.slice(0,-1)
  let code = 'ProductionTaskOrder'
  tableTitleSet.value.open(tableTitleList.value, code)
}

// // 获得表格的各种操作
const { getList } = tableMethods

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


const selectIdList = ref([])//选中的数据id数组
/** 派工/查看操作 */
const { push } = useRouter() // 路由
const openForm = (type,id) => {
  if( usTableoperation.value.selections.some(function check(item){
    return item.dictProductiveTaskStatus==30 ||item.dictProductiveTaskStatus==40 
  })){
    message.notifyError(t('已审核/审核中的任务不能进行批量派工'))
    return
  }
  if(type=='works'){
    selectIdList.value=[]
    console.log(usTableoperation.value.selections,'usTableoperation.value')
    if(usTableoperation.value.selections.length!==0){
      usTableoperation.value.selections.forEach(item=>{
        selectIdList.value.push(item.id)
    })
    }else{
      message.notifyError(t('请选择需要派工的任务'))
      return
    }
    console.log(selectIdList.value)
    push({
        path:'/produce/produce/workOrderManagement/productionTaskOrder/ProductionTaskOrderForm',
        query:{
          type,
          id:JSON.stringify(selectIdList.value)
        }
      })
  }else if(type=='work'||type=='details')
  push({
    path:'/produce/produce/workOrderManagement/productionTaskOrder/ProductionTaskOrderForm',
    query: {
      type,
      id
    }
  })
}

/**表头内部方法 */
const usTableoperation = ref()
const tableoperation = (table) => {
  usTableoperation.value = table
}


// 批量提交
const sumbitList = ref([])// 批量提交的数据数组
const sumbit = async ()=>{
  if( usTableoperation.value.selections.some(function check(item){
    return item.dictProductiveTaskStatus==20 ||item.dictProductiveTaskStatus==30 || item.dictProductiveTaskStatus == 40
  })){
    message.notifyError(t('待派工/已审核/审核中的任务不能进行批量提交'))
    return
  }
  sumbitList.value=[]
  sumbitList.value = usTableoperation.value.selections
  if(sumbitList.value.length!==0){
    let reqData ={
      submitFlag:1,
      updateList:sumbitList.value
    }
    console.log(reqData)
  await ProductionTaskOrderApi.putProductionTaskOrderList(reqData)
  message.success(t('提交成功'))
  getList()
  }else{
    message.notifyError(t('请选择需要提交的任务'))
  }
  clearSelectData()
}


// 提交
const sumbitRow = async(row)=>{
  const sumbitRowData=ref([])
  sumbitRowData.value.push(row)
  let reqData ={
      submitFlag:1,
      updateList:sumbitRowData.value
    }
    console.log(reqData,'reqData')
  await ProductionTaskOrderApi.putProductionTaskOrderList(reqData)
  message.success(t('已提交'))
  getList()
}

// 清空多选
const clearSelectData = ()=>{
  usTableoperation.value.selections = []
  usTableoperation.value.clearTableSelect()
}

// 下载
const downloadFun = async () => {
    const val = exportRef.value.params
    let params = {
      fileName: val.name,
      ids: ''
    }
    if (val.range === 'all') {
      params.ids = []
    } else {
       params.ids = usTableoperation.value.selections.map( item => item.id)
    }
    ProductionTaskOrderApi.exportProductionTaskOrder(params).then(res=>{
      download.excel(res, val.name)
      clearSelectData()
    })
  }

  // 获取搜索栏中状态的选项
const stateOptionsList = ref([])
const getStateOptions = async()=>{
  const res = await getIntDictOptions('productive_task_status')
  res.forEach((item)=>{
    console.log(item.value,'item')
    if([10,20,30,40,50,60].includes(item.value)){
      stateOptionsList.value.push(item)
      console.log(stateOptionsList.value,'ssssss')
}
  })
}

/** 初始化 **/
const tableHeight = ref(0)
onMounted( async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
     tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
  await getLabelAll()
  await getStateOptions()
  getList() 
})

</script>
<style lang="scss" scoped>
 .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  </style>